package reflect;

import day06.Methoddemo;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Scanner;

/**
 * 通过反射调用方法
 * 1、得到类对象
 */
public class ReflectDemo3 {
    public static void main(String[] args) {
        try {
            Class class1 = Class.forName("reflect.Person");
            Constructor constructor = class1.getConstructor(String.class,int.class);
            Object o1 =constructor.newInstance("张三",29);
            Method method1 = class1.getDeclaredMethod("hehe");
            method1.setAccessible(true);
            method1.invoke(o1);
            method1.setAccessible(false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入类名：");
            Class cls = Class.forName(scanner.nextLine());
            System.out.println("请输入方法名");
            Method method = cls.getMethod(scanner.nextLine());
            Constructor constructor = cls.getConstructor(String.class,int.class);
            method.invoke(constructor.newInstance("张三",29));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
